import { useState, useEffect, useContext, useRef } from 'react';
import { NavBar, Modal, Popup, Form, Input, List, Button, InfiniteScroll, Checkbox, DotLoading, Toast, SearchBar } from 'antd-mobile';
import { SearchBarRef } from 'antd-mobile/es/components/search-bar'
import { AddCircleOutline } from 'antd-mobile-icons';

import AvatarImage from '../AvatarImage';
import { MySdkStoreContext } from '../../context';

import './style.scss';

interface PropsType {
  visible: boolean,
  title: string;
  cid: string;
  getListApi: string,
  listFilterFunc: (items: any[]) => any[];
  onOk: (selectedItem: any[]) => void;
  onClose: () => void;
}

export default function(props: PropsType) {
  const mySdkStore = useContext(MySdkStoreContext);
  const { visible, title, cid, getListApi, onOk, onClose, listFilterFunc } = props;
  // 已选中的用户
  const [selectedContactor, setSelectedContactor] = useState([]);
  const [list, setList] = useState([]);
  const [pagination, setPagination] = useState({});
  const [addUserForm] = Form.useForm();
  const searchRef = useRef<SearchBarRef>(null);
  const [keyword, setKeyword] = useState('');

  useEffect(() => {
    if (searchRef?.current) {
      searchRef.current.focus();
    }
  }, [searchRef])

  const handleSearch = async () => {
    if (!keyword) {
      return;
    }

    try {
      const res = await mySdkStore.sdk.searchUser({ searchKey: keyword, pageIndex: 1, pageSize: 20 });
      setList(res.rows.map(user => ({...user, ...user.member})));
      setPagination({});
    } catch(e: any) {
      Toast.show(e.errorMessage || '操作失败');
    }
  }

  const handleSearchCancel = () => {
    if (keyword) {
      setKeyword('');
      getList(1);
    }
  }

  const getList = async (pageIndex) => {
    const data = await mySdkStore.sdk[getListApi]({ cid, pageIndex, pageSize: 20 });
    const { rows = [], next, current, totalItemCount } = data;
    let newList = rows;
    if (listFilterFunc) {
      newList = listFilterFunc(rows);
    }
    setList(pageIndex === 1 ? newList : [...list, ...newList]);
    setPagination({ pageIndex: current, next: +next, totalItemCount });
  }

  useEffect(() => {
    getList(1);
  }, []);

  // 点击”确定“按钮事件
  const handleOk = () => {
    const items = [...selectedContactor, mySdkStore.mockConfig.userId].map(userId => ({ userId }));
    onOk(items);
  }

  // 点击”添加用户“事件
  const handleAddUser = () => {
    Modal.confirm({
      title: '添加用户',
      content: <Form form={addUserForm}>
        <Form.Item name="invitedUserId" label={null} rules={[{ required: true, message: '请输入用户ID'}]}>
          <Input placeholder="请输入用户ID" />
        </Form.Item>
      </Form>,
      onConfirm: () => new Promise(async (resolve, reject) => {
        try {
          const values = await addUserForm.validateFields();
          await mySdkStore.sdk.addFriend({ ...values });
          Toast.show('好友请求已发送');
          resolve(true);
          getList(1);
        } catch(e: any) {
          if (e.errorMessage) {
            Toast.show(e.errorMessage);
          }
          reject();
        }
      }),
    });
  }

  // 渲染数据列表
  const renderList = () => {
    return <List style={{ '--border-inner': 0 }}>
      {list.map(item => {
        return mySdkStore.mockConfig.userId !== item.userId ? (
          <List.Item
          key={item.userId}
          prefix={
          <>
            <Checkbox value={item.userId} style={{ marginRight: 12, marginBottom: 10 }} />
            <AvatarImage
              src={item.avatarUrl}
              style={{ display: 'inline-block', borderRadius: 8 }}
              fit='cover'
              width={36}
              height={36}
              nickName={item.nickName}
              userName={item.userName}
              userId={item.userId}
            />
        </>}>{ item.nickName || item.userName || item.userId }</List.Item>
        ) : null
      })}
    </List>
  }

  return visible ? <Popup
    visible={true}
    bodyClassName="popupbody" style={{ '--z-index': 999 }}>
      <div className="selectGroupContractorComponent">
        <NavBar onBack={onClose} style={{ background: '#fff', border: 'none' }}>{ title }</NavBar>
        <SearchBar ref={searchRef} placeholder="搜索" onChange={val => setKeyword(val)} onSearch={() => handleSearch()} onClear={handleSearchCancel} onCancel={handleSearchCancel} showCancelButton style={{ margin: '0 12px 12px 12px', background: '#fff' }} />

        {/* todo: queryUsers 没有关键词搜索参数 */}
        {/* <SearchBar className="searchBar" placeholder="搜索" onSearch={handleSearch} /> */}
        <List>
          <List.Item>
            <a onClick={handleAddUser}><AddCircleOutline style={{ marginRight: 12 }} />添加用户</a>
          </List.Item>
        </List>
        <Checkbox.Group onChange={(val) => setSelectedContactor(val)}>
          {renderList()}
          {keyword ? null : <InfiniteScroll loadMore={() => getList(pagination.pageIndex + 1)} hasMore={list.length && pagination.totalItemCount > list.length}>
            {pagination.totalItemCount > list.length ? (
                <>
                  <span>Loading</span>
                  <DotLoading />
                </>
              ) : ''}
          </InfiniteScroll>}
        </Checkbox.Group>
        <div className="bottomOperationBar">
          <div style={{ lineHeight: '29px' }}>已选择：{selectedContactor.length}人</div>
          <Button color="primary" size="small" onClick={handleOk} disabled={!selectedContactor.length }>确定</Button>
        </div>
      </div>
  </Popup> : null;
}